import { NavBar, Space, Toast, Form, Input, Button } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'

import { login } from '@/api/login'
import { setInfo } from '@/store/modules/user'
import { useDispatch } from 'react-redux'

export default function Login () {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const location = useLocation()

  const [form] = Form.useForm()

  const [loginname, setLoginname] = useState('17704051019')
  const [password, setPassword] = useState('123456')

  const back = () => {
    navigate('/')
  }

  useEffect(() => {
    form.setFieldsValue({
      loginname,
      password
    })
  }, [])

  const onFinshed = async (val: { loginname: string; password: string }) => {
    await form.validateFields()
    console.log(val)

    const res = await login(val)
    if (res.code === 200) {
      dispatch(setInfo(res.data))

      Toast.show({
        icon: 'success',
        content: res.message,
        duration: 800
      })
      setTimeout(() => {
        // // console.log(location)
        // const a = location.search.split('?')
        // // console.log(a)
        // // const b = a[1].split('=')[1]
        // // console.log(b)
        // const c = a[2] ? a[1].split('=')[1] + '?' + a[2] : a[1].split('=')[1]
        // // console.log(c)
        // navigate(c)
        if (location.search) {
          const searchParams = new URLSearchParams(location.search)
          navigate(searchParams.get('redirect') ?? '/')
        } else {
          navigate('/')
        }

        // navigate('/')
      }, 800)
    } else {
      Toast.show({
        icon: 'fail',
        content: res.message,
        duration: 800
      })
    }
  }

  return (
    <div>
      <NavBar style={{ backgroundColor: 'white' }} onBack={back}>
        登录
      </NavBar>
      <Space />
      <Form
        style={{ fontSize: 14 }}
        form={form}
        layout='horizontal'
        onFinish={onFinshed}
        footer={
          <Button
            block
            type='submit'
            color='primary'
            size='large'
            style={{ borderRadius: 50 }}
          >
            登录
          </Button>
        }
      >
        <Form.Item
          name='loginname'
          label='手机号'
          rules={[{ required: true, message: '手机号不能为空' }]}
        >
          <Input placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item
          name='password'
          label='密码'
          rules={[
            { required: true, message: '密码不能为空' },
            { min: 5, max: 10, message: '密码只能5-10位' }
          ]}
        >
          <Input placeholder='请输入密码' />
        </Form.Item>
      </Form>
    </div>
  )
}
